////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.stock;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.Button;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.ProgressDialog;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.HttpHelper;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.Data;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.MessageHistoryListAsyncTask;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.WebViewCopy;

/**
 * 
 * @author haibo
 * 
 *  for list item  named  "Instant Market"
 *
 */
public class NewStockNewsActivity extends BaseActivity
{

	//private static final int CONNECTION_TIMEOUT = 1000 *10;  //10 seconds;
	protected static final String			TAG						= NewStockNewsActivity.class.getSimpleName();
	public  static String				_stockCode				= "";																						//modify in the run time;

	
	public static final String			KEY_FOR_CURRENT_STOCK_CODE	= "key.current.code";

	
	private Button						_toolBtnReturn;

	private TextView					_top_bar_title;
	
	private WebView			_webView;
	private String  _webViewUrl = "";
	private  WebViewCopy  _webViewCopy;

	

	private Context					_context;
	
	public static  boolean _isComeFromBack = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.stock_news_list);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				// BMP Mode  by ouyangzhihui 2011-10-13
				Class<? extends Activity>_cls = CurrentStockInfoActivity.class;
				if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
				{
					_cls = BMPCurrentStockInfoActivity.class;
				}
				Intent intent = new Intent(getApplicationContext(), _cls);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(_cls, intent);
			}
		});

		_messageHandler = null; //this activity no need it.
		

		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);
		_context = this;
		
		_webView=(WebView)findViewById(R.id.webview);
		WebSettings webSettings =  _webView.getSettings();
		
		webSettings.setBuiltInZoomControls(true);
		
//		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//		webSettings.setUseWideViewPort(true);
		webSettings.setRenderPriority(RenderPriority.HIGH);
		webSettings.setJavaScriptEnabled(true);
		_webView.setHorizontalScrollBarEnabled(false);

		
		_webView.setWebViewClient(new WebViewClient(){       
		                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
				                	  if(!SystemInfo.isNetworkingConnected(_context)){
				                	         new CustomizeDialog(NewStockNewsActivity.this.getParent() == null ? NewStockNewsActivity.this :  NewStockNewsActivity.this.getParent() ,getString(R.string.info), getString(R.string.service_not_available), 
				             						getString(R.string.ok)).show();
				                	         return true;       
			                	         }
		                	         TDStockLog.d(TAG, url);
		                	         view.loadUrl(url);
			                         return true;       
			                    }       
			         });
		_webViewCopy  = new WebViewCopy(this, _webView);
		
		
		
	}

	protected Context getMyOwnContext()
	{
		return _context;
	}

	

	
	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		 ProgressDialog.dismissAll();
	}

	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		resetTitle();
		
		TDStockLog.d(TAG, "ready to fetch data again!");
		getNews();

	}

	/*public static void show(Context context, String stockCode)
	{
		_stockCode = stockCode;
	

		Intent intent = new Intent(context,
				CurrentStockNewsListActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		View view = StockGroup.group.getLocalActivityManager().startActivity(
				CurrentStockNewsListActivity.class.getSimpleName(), intent)
				.getDecorView();
		StockGroup.group.setContentView(view); //modified by haibo, 2011-05-16

	}*/
	
	
	

	private void resetTitle()
	{
		_top_bar_title.setText((((ITDLApplication) getApplicationContext())
				.getCurrentStockName()));
		_top_bar_title.postInvalidate();
	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return StockGroup.GetActivityGroupHostControl();
	}
	
	
	
	
	public void onCreateContextMenu(ContextMenu menu, View v,  
            ContextMenuInfo menuInfo) {  
		_webViewCopy.onCreateContextMenu(menu, v, menuInfo,COPY,getString(R.string.copy));
        super.onCreateContextMenu(menu, v, menuInfo);  
}
	
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		
			super.onCreateOptionsMenu(menu);
			
			{ 
				menu.add(0, COPY,3, getString(R.string.copy));
				MenuItem mItem = menu.findItem(COPY);
				mItem.setIcon(R.drawable.copy32x32);
			}
		
			{
				menu.add(0, BACK,4, getString(R.string.back));
				MenuItem mItem = menu.findItem(BACK);
				mItem.setIcon(R.drawable.option_menu_back_img);
				
			}
			
			{
				menu.add(0, FORWARDING, 5, getString(R.string.forwarding));
				MenuItem mItem = menu.findItem(FORWARDING);
				mItem.setIcon(R.drawable.option_menu_forwarding_img);
				
			}
			
			
			
			
			
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int c, MenuItem iItem)
	{
		TDStockLog.d(TAG, "onMenuItemSelected");
		super.onMenuItemSelected(c, iItem);
		if(iItem.getItemId() == COPY && _webView != null ) {
			//WebViewCopy.emulateShiftHeld(_webView);
			WebViewCopy.selectAndCopyText(_webView);
		}
		else if( iItem.getItemId() == BACK && _webView !=  null && _webView.canGoBack() ) {
			_webView.goBack();
		}
		else if( iItem.getItemId() == FORWARDING && _webView !=  null && _webView.canGoForward()) {
			_webView.goForward();
		}
		
		
		return true;
	}	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
         TDStockLog.d(TAG, "onOptionsItemSelected");
		if(item.getItemId() == COPY && _webView != null ) {
			WebViewCopy.selectAndCopyText(_webView);
		}
		else if( item.getItemId() == BACK && _webView !=  null && _webView.canGoBack() ) {
			_webView.goBack();
		}
		else if( item.getItemId() == FORWARDING && _webView !=  null && _webView.canGoForward()) {
			_webView.goForward();
		}
		return true;
	}
	
	
	
	
	
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		  if( menu  != null && _webView != null) {
        	  MenuItem  backMenu =menu .findItem(BACK);
        	   backMenu.setEnabled(_webView.canGoBack());
        	   TDStockLog.d(TAG, " set back  menu  as "  +  backMenu.isEnabled());
        	   
        	   MenuItem  forwardingMenu =  menu .findItem(FORWARDING);
        	   forwardingMenu.setEnabled(_webView.canGoForward());
        	   TDStockLog.d(TAG, " set forwarding Menu  as "  +  forwardingMenu.isEnabled());
         }
		
		return super.onPrepareOptionsMenu(menu);
	}

	private void getNews(){
		new MessageHistoryListAsyncTask(this.getParent(), ""){
			  private String  newsUrl;
			  private    boolean isFinished ;
			@Override
			protected Void doInBackground(String... params) {
				// TODO Auto-generated method stub
				 super.doInBackground(params);
				 if(!SystemInfo.isNetworkingConnected(_context)){
					 	newsUrl =  "";
			    	}
				 	newsUrl =HttpHelper.isServerAvaiable(Data.getNewVersionNewsContentURL(_context, _stockCode), _context, 1);
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				//Log.d(TAG, result);
				isFinished = false;
				_webViewUrl = newsUrl;
				TDStockLog.d(TAG, newsUrl==null?"temp is null":newsUrl);
				if(!"".equals(newsUrl)&&null!=newsUrl){
				   setWebViewContent(newsUrl);
				   isFinished = true;
				}else{
					isFinished = false;
					setWebContextDefault();
				}
				
			}
			   
		   }.execute();
	  }
	
	public void setWebViewContent(final String url){
		  if (_webView != null)
			{

				//_webView.getSettings().setBuiltInZoomControls(true);
				//_webView.getSettings().setJavaScriptEnabled(true);
		    	_webView.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						_webView.loadUrl(url);
					}
				},400);/*_webView.loadUrl(url);*/
			}
	}
	public void setWebContextDefault(){
		if(_webView!=null){
			 String summary="<html><head></head><body>"+this.getString(R.string.service_not_available)+"</body></html>";
			   TDStockLog.d(TAG, "content=" + summary);
				//_webView.getSettings().setBuiltInZoomControls(true);
				//_webView.getSettings().setJavaScriptEnabled(true);
				_webView.loadDataWithBaseURL(null, summary, "text/html","utf-8", null);
		}
	}
	
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		getIntent().putExtras(intent);   //update the current intent
	}
	
	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo) {

		//super.NetworkChange_Response(iConnect, iNetInfo);
		if(iNetInfo.isAvailable() || iNetInfo.isConnected()) {
			getNews();
		}
		
	}
	
	@Override
	public void onBackPressed() {
		if(_webView !=  null && _webView.canGoBack()  &&  !_webView.getUrl().equals(_webViewUrl)) {
				_webView.goBack();
				return ;
		 }
		if(_toolBtnReturn != null) {
			_toolBtnReturn.performClick();
		}
	}
	
	

}
